package com.bckj.fastboot.core.extra.extpt;

import com.bckj.fastboot.core.extra.stage.BaseStageContext;
import com.bckj.fastboot.core.extra.stage.StageRepository;
import org.springframework.util.Assert;

public class DynamicProcExtPtHandler extends DynamicExtPtHandler {

    private final ExtPtProcHandler procHandler;


    public DynamicProcExtPtHandler(StageRepository stageRepository, ExtPtProfile profile, ExtPtProcHandler procHandler) {
        super(stageRepository, profile);
        this.procHandler = procHandler;
    }

    @Override
    protected void check(ExtPtProfile.Method em) {
        if (em.getType() == ExtPtProfile.TYPE_PROCESS) {
            Assert.hasText(em.getProcessId(), "processId can not be null");
        } else {
            Assert.notEmpty(em.getStages(), "stages can not be empty");
        }
    }

    @Override
    protected Object invoke(ExtPtProfile.Method em, BaseStageContext arg) throws Throwable {
        if (em.getType() == ExtPtProfile.TYPE_PROCESS) {
            return invokeProcess(em, arg);
        }
        return invokeChain(em, arg);
    }

    Object invokeProcess(ExtPtProfile.Method em, BaseStageContext arg) throws Throwable {
        procHandler.handle(em.getProcessId(), arg);
        return null;
    }
}
